package com.chenyun.mq.rabbitmq.config;

import com.chenyun.mq.rabbitmq.handler.DefaultConfirmCallback;
import com.chenyun.mq.rabbitmq.handler.DefaultReturnsCallback;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * @author: lonni
 * @CreateTime: 2023-12-02  16:48
 * @Description:
 */
@Configuration
public class RabbitMqConfig {

    /**
     * 使用发布确认方式
     * @param connectionFactory
     * @return
     */
    @Bean("rabbitTemplateConfirm")
    public RabbitTemplate rabbitTemplateConfirm(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        //确认消息送到交换机(Exchange)回调
        rabbitTemplate.setConfirmCallback(new DefaultConfirmCallback());

        //设置开启Mandatory,才能触发回调函数,无论消息推送结果怎么样都强制调用回调函数
        rabbitTemplate.setMandatory(true);
        //确认消息送到队列(Queue)回调
        rabbitTemplate.setReturnCallback(new DefaultReturnsCallback());
        return rabbitTemplate;
    }


    /**
     * 不适用发布确认方式
     * @param connectionFactory
     * @return
     */
    @Bean("rabbitTemplate")
    @Primary
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        return rabbitTemplate;
    }

}
